package com.backend.mzyf.interceptor;


import com.backend.mzyf.Utils.ResourceUtil;
import com.backend.mzyf.entity.ActiveUser;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        String url = httpServletRequest.getRequestURI();
        List<String> anonymousUrls = new ResourceUtil().getUrls("anonymousUrl");

        //判断访问的地址是否为匿名访问地址
        for (String anonymousUrl:anonymousUrls) {
            if (url.indexOf(anonymousUrl) >=0){
                return true;
            }

        }

        HttpSession session = httpServletRequest.getSession();
        //判断session中是否有值，如果有值就放行
        ActiveUser activeUser = (ActiveUser) session.getAttribute("activeUser");
        if (activeUser != null){
            return true;
        }

        httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login");

        return false;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("HandlerInterceptor2...postHandle");
    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("HandlerInterceptor2...afterCompletion");
    }
}
